/**
 * 不知道该怎么描述。TODO
 * 反正就是想重写掉一部分jquery的方法
 * @author 赖伟威 l.weiwei@163.com 2016-08-17
 */
var __$$ = {
	ajax: function(settings) {
		return {
			responseText: null,
			done: function(cb) {}
		};
	},
	when: function() {
		return {
			done: function() {}
		};
	},
	__cache:{}
};
var __$ = {
	ajax: function(settings) {
		settings = settings || {
			url: '',
			dataType: 'json',
			async: true,
			data: {}
		};
		settings.data = settings.data || {};
		var key = settings.key || settings.url;
		if(settings.async == false) {
			var abort = false;
			var __cache = $.__cache;// 因为这个js文件要依赖jquery，所以约定用$对象放置缓存
			var done = function(cb){
				cb(__cache[key]);
			};
			
			if (!__cache[key] && typeof(require) === 'function') {
				var API = require('../../server/api.js');
				var data = settings.data;
				done = function(cb) {
					cb = cb || function(data) {};
					// 此处调用的是服务端的API处理类
					API.invoke(settings.url, data, function(result) {
						__cache[key] = JSON.parse(result);
						cb(__cache[key]);
					});
				};
			}
			
			return {
				state: function(){return 4},
				abort: abort,
				done: done
			};
		} else {
			return __$$.ajax(settings);
		}
	},
	when: function() {
		var datas = [];
		for(i = 0; i < arguments.length; i++) {
			datas.push([{},'',{}]);
			var arg = arguments[i];
			if(arg.responseText) {
				try {
					var obj = JSON.parse(arg.responseText);
					datas[i] = [obj, 'success', {}];
				} catch(e) {}
			} else {
				datas[i] = [arg,'',{}];
			}
		}

		return {
			done: function(cb) {
				var l = datas.length;
				var count = l;
				var check = function() {
					count--;
					if (count == 0) {
						cb.apply(this, datas);
					}
				}.bind(this);
				for(j = 0; j < l; j++) {
					var v = datas[j][0];
					if (v.abort && v.abort == true) {
						continue;
					}
					// 处理那些异步请求，每次请求数据回来都callback一次
					if(typeof(v.state) == 'function' && typeof(v.done) == 'function') {
						v._idx = j;
						v.done(function(data) {
							if (data) {
								datas[v._idx] = [data, 'success', {}];
							}
							check();
						});
					}
				}
			}
		};
	}
};

if(typeof($) != 'undefined') {
	__$$.ajax = $.ajax;
	__$$.when = $.when;
	$.ajax = __$.ajax;
	$.when = __$.when;
} else {
	$ = __$;
};

if (typeof($.__cache) == 'undefined') {
	$.__cache = __$$.__cache
}

if (typeof(module) != 'undefined') {
	module.exports = $;
}